package org.agiletestplus.client.ui;

import org.agiletestplus.client.objects.Project;
import org.damour.base.client.service.BaseServiceCache;
import org.damour.base.client.ui.IGenericCallback;
import org.damour.base.client.ui.buttons.Button;
import org.damour.base.client.ui.dialogs.IDialogCallback;
import org.damour.base.client.ui.dialogs.MessageDialogBox;
import org.damour.base.client.ui.dialogs.PromptDialogBox;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ProjectPanel extends VerticalPanel {
	public ProjectPanel(final IGenericCallback<Project> callback, final Project project) {
		add(new Label("Project Name: " + project.getName()));
		add(new Label("Project Description: " + project.getDescription()));
		HorizontalPanel panel = new HorizontalPanel();
		Button editButton = new Button("Edit Project");
		panel.add(editButton);
		Button deleteButton = new Button("Delete Project");
		panel.add(deleteButton);
		add(panel);
		
		editButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				callback.invoke(project);
			}
		});
		
		deleteButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				
				PromptDialogBox dialog = new PromptDialogBox("Delete Project", "Yes", null, "No", true, true);
				dialog.setCallback(new IDialogCallback() {
				      public void okPressed() {
				    	  AsyncCallback<Void> deleteCallback = new AsyncCallback<Void>() {
								@Override
								public void onFailure(Throwable caught) {
									MessageDialogBox dialog = new MessageDialogBox("Error", "An error occurred while deleting the project: " + caught.getMessage(), true, true, true);
									dialog.center();
								}

								@Override
								public void onSuccess(Void result) {
									MessageDialogBox dialog = new MessageDialogBox("Success", "Project deleted.", true, true, true);
									dialog.center();
									callback.invoke(null);
								}
							};
							BaseServiceCache.getService().deletePermissibleObject(project, deleteCallback);
				      }

				      public void cancelPressed() {
				      }
				    });
			    dialog.setContent(new HTML("Are you sure you want to delete the project?"));
			    dialog.center();
			}
		});
		
	}
}
